package com.zbdx.dao.impl;

import com.zbdx.dao.CarDao;
import com.zbdx.domain.User;
import com.zbdx.domain.merchant;
import com.zbdx.domain.productVo;
import com.zbdx.util.DruidUtil;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.sql.SQLException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.List;

/**
 * @Author ghp
 * @Creat 2024/9/18 10:48
 * @Version 1.0
 * Description:
 */
public class CarDaoImpl implements CarDao {
    private QueryRunner qr = new QueryRunner(DruidUtil.getDataSource());

    @Override
    public List<productVo> selectGoodsByUsername(String username) throws SQLException {

        String sql = "SELECT id FROM users2 WHERE username=?";
        User user = qr.query(sql, new BeanHandler<>(User.class), username);
        int userId = user.getId();

        sql = "SELECT * FROM product WHERE user_id=?";
        List<productVo> productVoList = qr.query(sql, new BeanListHandler<productVo>(productVo.class), userId);

        for (productVo productVo : productVoList) {
            sql = "SELECT * FROM merchant WHERE MId=?";
            merchant mer = qr.query(sql, new BeanHandler<>(merchant.class), productVo.getMId());
            productVo.setMName(mer.getMName());
        }
        return productVoList;
    }


    @Override
    public int insertProduct(productVo productVo) throws SQLException {
        String sql="INSERT INTO product(PName,PType,PNum,PPrice,mid,PImage01,user_id) VALUES(?,?,?,?,?,?,?)";
        int row = qr.update(sql, productVo.getPName(), productVo.getPType(), productVo.getPNum(), productVo.getPPrice(),
                productVo.getMId(), productVo.getPImage01(), productVo.getUserId());
        return row;
    }

    @Override
    public boolean removeProduct(List<Integer> idList, int userId) throws SQLException {
        for (Integer pid : idList) {
            String sql = "DELETE FROM product WHERE user_id=? AND pid=?";
            qr.update(sql, userId,pid);
        }
        return true;
    }

    @Override
    public boolean addCar(List<productVo> productVoList) throws SQLException {
        LocalDate currentDate = LocalDate.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        String formattedDate = currentDate.format(formatter);
        for (productVo productVo : productVoList) {
            String sql="INSERT INTO t_order(orderPrice,orderTime,orderType,order_image_url,orderStatus,orderName) VALUES(?,?,?,?,?,?)";
            qr.update(sql, productVo.getPPrice(), formattedDate, productVo.getPType(), productVo.getPImage01(), "待收货",productVo.getPName());
        }
        return true;
    }
}
